package com.threebrothers.lib_mvi.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

abstract class BaseLazyLoadFragment  : Fragment(){
    /**
     * 是否初始化
     */
    protected var isInit = false
    /**
     * 是否已完成加载
     */
    protected var isLoaded = false
    protected lateinit var mView : View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mView = getFragmentRootView(inflater,container,savedInstanceState)
        isInit = true
        prepareLoadData()
        initData()
        return mView
    }

    private fun prepareLoadData(){
        if (!isInit) return
        if (userVisibleHint){//可见
            lazyLoad()
            isLoaded = true
        }else{
            if (!isLoaded){
                stopLoad()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isInit = false
        isLoaded = false
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEnv()
        initData()
        initEvent()
    }
    /**
     * 延时加载
     */
    abstract fun lazyLoad()

    /**
     * 停止加载可以用于释放资源
     */
    protected fun stopLoad(){}

    protected open fun initEnv(){}
    protected open fun initEvent() {}

    protected open fun initData(){}

    protected open fun initView() {}
    /**
     * 获得Fragment视图View
     */
    abstract fun getFragmentRootView(inflater : LayoutInflater,
                                     container : ViewGroup?,
                                     savedInstanceState : Bundle?):View

    /**
     * 查找并获取资源
     */
    protected fun <T : View> findViewById(id: Int): T {
        return mView.findViewById(id)
    }
    /**
     * 显示提示消息
     */
    protected fun showMsg(msg : String){
        if (activity is BaseActivity){
            (activity as BaseActivity).showMsg(msg?:"")
        }
    }
}